package com.sam.test.springboot.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sam.test.springboot.pool.TaskService;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("test")
@Slf4j
public class PoolTestController {

	@Autowired
	private TaskService serviceImpl;
	
	ObjectMapper mapper = new ObjectMapper();
	
	@RequestMapping("/execute2tasks")
	@ResponseBody
	public String execute2tasks() {
	    try {
	        List<Future<String>> tasks = new ArrayList<>();
	        List<String> results = new ArrayList<>();
	        tasks.add(serviceImpl.doTask1());
	        tasks.add(serviceImpl.doTask2());
	        //各个任务执行完毕
	        for (Future<String> task : tasks) {
	            //每个任务都会再在此阻塞。
	            results.add(task.get());
	        }
	        log.info("All tasks finished!");
	        log.info("执行结果：{}", mapper.writeValueAsString(results));
	        return "success";
	    } catch (InterruptedException e) {
	        e.printStackTrace();
	    } catch (ExecutionException e) {
	        e.printStackTrace();
	    } catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	    return "failure";
	}

}
